var App = App || {};
App.formatTime = function (time) {
    let now_time = Date.parse(new Date()) / 1000;
    time = parseInt((now_time - time));
    if (time < 60 * 10) {
        return '刚刚';
    } else if ((time < 60 * 60) && (time >= 60 * 10)) {
        return Math.floor(time / 60) + "分钟前";
    } else if ((time < 60 * 60 * 24) && (time >= 60 * 60)) {
        return Math.floor(time / 60 / 60) + "小时前";
    } else {
        return Math.floor(time / 60 / 60 / 24) + "天前";
    }
};
App.history = {
    add: function () {
        if (typeof window['comic_data'] === 'undefined') {
            return;
        }
        let comic_data = window['comic_data'];
        delete comic_data['book_images'];
        this.comic_list[comic_data['id']] = comic_data;
        this.set();
    },
    set: function () {
        window.localStorage.setItem(this.k, JSON.stringify(this.comic_list));
    },
    isEmpty: function () {
        return Object.keys(this.comic_list).length === 0
    },
    show: function () {
        if (typeof window['comic_data'] === 'undefined') {
            return;
        }
        let o = 'https://ae01.alicdn.com/kf/H9df823ccbfcf4f88aec3b3be4b65a699d.jpg';
        let data = window['comic_data'];
        for (i in data['book_images']) {
            let $img = $('<img />', {
                'class': 'img-responsive',
                'src': o,
                'data-original': data['book_images'][i]
            });
            $('.book-content').append($img);
        }
        $('.img-responsive').lazyload({effect: 'fadeIn'});
    },

    init: function () {
        this.show();

        let comic_list = window.localStorage.getItem(this.k);
        if (!comic_list) {
            this.comic_list = {};
        } else {
            this.comic_list = JSON.parse(comic_list)
        }
        if (App.isGuest(false)) {
            this.add();
            this.init_list();

            if (!this.isEmpty()) {
                $('.nav-item-history .empty').addClass('d-none');
            }
            return;
        }
        if (!this.isEmpty()) {
            for (i in this.comic_list) {
                console.log(i)
            }
            // this.comic_list = {}
            // this.set()
        }
    },
    init_list: function () {
        if (this.isEmpty()) {
            return
        }
        let template =
            '<div class="tile font-1" id="book-{id}" data-id="{id}">\
                <div class="tile-icon mr-2 text-muted">{t}</div>\
                <div class="tile-content-2 text-ellipsis">\
                    <a class="text-normal hover" href="{book_url}">[{book_title}]</a>\
                </div>\
                    <div class="tile-content">\
                    <em class="text-muted">阅至: </em><a class="tooltip tooltip-top" data-tooltip="{book_item_name}" href="{book_item-url}">{book_item_name}</a>\
                </div>\
                <div class="tile-action">\
                    <a class="history-delete-local text-muted hover" href="javascript:void(0);"><i class="icon-trash-o"></i></a>\
                </div>\
            </div>';

        let p = /{([^}]*)}/g;
        for (let i in this.comic_list) {
            let item = this.comic_list[i];
            let html = template.replace(p, function (match, key, value) {
                if (key === 't') {
                    return App.formatTime(item['t']);
                }
                return item[key] ? item[key] : i;
            });
            $('.nav-item-history .panel-body').prepend(html);
        }
        this.bind_event();

    },
    bind_event: function () {
        let h = this;
        $(document).on('click', '.history-delete-local', function (e) {
            let $tile = $(this).parents('.tile');
            let $id = $tile.data('id');
            delete h.comic_list[$id];
            h.set();
            $tile.slideUp(800, function () {
                $tile.remove();
            });
            return false;
        });
    },

};
App.history.k = 'comic_list';

App.isJson = function (obj) {
    return typeof (obj) === "object" && Object.prototype.toString.call(obj).toLowerCase() === "[object object]" && !obj.length;
};

App.tip = function (message, time) {
    time = time || 4000;
    let body = $('body');
    let obj = body.find('.toast');
    if (!obj.length) {
        obj = $('<div/>', {'class': 'toast'});
        body.append(obj);
    }
    obj.html(message);
    window.setTimeout(function () {
        obj.remove();
    }, time);
};

App.sendTime = function ($this) {
    let $text = $this.text();
    let n = 60;
    let interval = window.setInterval(function () {
        n--;
        if (n <= 0) {
            window.clearInterval(interval);
            $this.removeClass('disabled');
            $this.text($text);
            return;
        }
        $this.text(n + '秒后重试');
    }, 1000);
};

App.isDisabled = function ($this) {
    return $this.hasClass('disabled');
};

App.from = function ($this, callback) {
    if (App.isDisabled($this)) {
        return false;
    }

    let form = $this.parents('form');
    $this.addClass('disabled').addClass('loading').attr('disabled', 'disabled');
    $.post(form.attr('action'), form.serialize(), function (res) {
        if (!App.isJson(res) || res['code'] > 0) {
            $this.removeClass('disabled').removeClass('loading').removeAttr('disabled');
            App.tip(res['msg']);
            return;
        }
        if (callback) {
            callback(res)
            return;
        }

        window.setTimeout(function () {
            let redirect = $this.attr('redirect') || res['redirect'] || false;
            if (redirect) {
                window.location.href = redirect;
            } else {
                window.location.reload();
            }
        }, 2000);
    });
    return false;
};

App.isGuest = function (open_modal = true) {
    if (!window['user']['id']) {
        if (open_modal) {
            $('.ajax-login').trigger('click');
        }
        return true;
    }
    return false;
};
App.uid = window['user']['id'];

// $(document).ready(function () {
//     let e = $('.qr_code');
//     e.length && $.each(e, function (e, i) {
//         let n = $(i), o = n.data("text");
//         n.qrcode({text: o})
//     });
// });

$(function () {
    App.history.init();

    $.debounce = function (idle, action) {
        let last;
        return function () {
            let ctx = this, args = arguments;
            clearTimeout(last);
            last = setTimeout(function () {
                action.apply(ctx, args)
            }, idle)
        }
    };

    $('.lazy').lazyload({
        effect: "fadeIn"
    });

    $(document).on('click', '.do-ajax-login', function () {
        $('.ajax-login').trigger('click');
    });

    $(document).on('click', '.scroll-up', function () {
        $('html,body').animate({scrollTop: '0px'}, 800);
    });

    $(document).on('click', '.scroll-down', function () {
        $('html,body').animate({scrollTop: $('.footer').offset().top}, 800);
    });

    $(document).on('click', '.nav-link-search', function () {
        let $this = $(this);
        let icon = $this.find('i');
        if (icon.hasClass('icon-search')) {
            icon.removeClass('icon-search').addClass('icon-close')
        } else {
            icon.removeClass('icon-close').addClass('icon-search')
        }
        $('.search-dialog').slideToggle();
        return false;
    });

    $(document).on('keyup', '.form-input-search', function (e) {
        if (e.keyCode === 13) {
            $(this).parent('form').submit();
        }
    });

    $(document).on('click', '.captcha', function () {
        let $this = $(this);
        let url = $this.attr('src');
        if (url.indexOf('?') !== -1) {
            url = url.substr(0, url.indexOf('?') + 1);
        }
        $this.attr('src', url + '?v=' + Math.random());
    });

    $(document).on('click', '.comment .reply', function () {
        let $this = $(this);
        let $parent = $this.parents('.comment');
        let $form = $('.comment-form');
        $('html,body').animate({scrollTop: $form.offset().top - 150}, 800);
        $form.find('[name="parent_id"]').val($parent.attr('id'));
        $form.find('[name="content"]').focus();
    });

    $('.raty').raty({
        starType: 'i',
        starHalf: 'icon-star-half-o',
        starOff: 'icon-star-o',
        starOn: 'icon-star',
        half: false,
        readOnly: function () {
            return $(this).data('only');
        },
        hints: ['很差', '无聊', '一般', '好看', '力荐'],
        click: function (score, env) {
            if (App.isGuest()) {
                return false;
            }
            let $this = $(this);
            $.get($this.data('href'), {'score': score}, function (res) {
                App.tip(res['msg']);
                window.setTimeout(function () {
                    window.location.reload();
                }, 2000);
            });
            return false;
        }
    });

    $(document).on('click', '.book-item-action a.sort', function () {
        let $list = $('.book-item-list .columns');
        $list.append($list.find('div').get().reverse());
        $(this).addClass('d-none').siblings('.sort').removeClass('d-none');
    });

    $(document).on('click', '.book-item-action a.expand', function () {
        $(this).addClass('d-none').siblings('.expand').removeClass('d-none');
        let container = $('.book-item-list');
        if (!container.hasClass('expand')) {
            container.addClass('expand');
            $('html,body').animate({scrollTop: container[0].scrollHeight}, 800);
        } else {
            container.removeClass('expand')
        }
    });

    $(document).on('click', '.favorite', function () {
        let $this = $(this);
        if (App.isGuest()) {
            return false;
        }
        $.get($this.data('href'), function (res) {
            if (res['code'] <= 0) {
                let t = $this.find('span').text();
                t = t === '取消收藏' ? '收藏' : '取消收藏';
                $this.find('span').text(t);
            }
            App.tip(res['msg']);
        });
        return false;
    });

    $(document).on('click', '.history-delete', function () {
        let $this = $(this);
        let $parent = $this.parents('.tile');
        $parent.slideUp('slow', function () {
            $parent.remove();
        });
        if (!App.isGuest(false)) {
            $.getJSON($this.data('href'));
        }
        return false;
    });

    $(document).on('click', '.ajax-modal', function () {
        let $this = $(this);
        let url = $this.data('href');
        if (url.length < 5) {
            return false;
        }
        $.get(url, function (html) {
            let $container = $("body").find('.modal-container')
            if (!$container.length) {
                $('body').append(html)
            } else {
                $container.html($(html).find('.modal-container').html())
            }
            let $modal = $('.modal');
            $modal.addClass('active');
            $container = $modal.find('.modal-container')
            $container.find('.btn-clear').on('click', function () {
                $modal.removeClass('active');
                $container.html('')
            });
        });
        return false;
    });

    $(document).on('click', ':submit, .submit, .modal :submit', function () {
        let $this = $(this);
        if (!$this.hasClass('btn-auth')) {
            if (App.isGuest()) {
                return false;
            }
        }
        App.from($this);
        return false;
    });

    $(document).on('click', '.bulb', function () {
        let $this = $(this);
        let logo = $('.navbar-brand img');
        let logo_src = logo.attr('src');
        logo_src = logo_src.indexOf('logo2') !== -1 ? logo_src.replace('logo2', 'logo') : logo_src.replace('logo', 'logo2');

        if ($("body").hasClass('dark')) {
            $('body').removeClass('dark');
            $this.attr('data-tooltip', '关灯');
        } else {
            $('body').addClass('dark');
            $this.attr('data-tooltip', '开灯');
        }
        logo.attr('src', logo_src);
    });

    $(document).on('click', '.book-item-list-button', function () {
        $('.book-item-dialog').slideToggle();
    });

    $('body').on('mousemove', function (e) {
        let y = e.clientY;
        let wh = $(window).height();
        if (y < 50 || y > wh - 50) {
            $('.header').stop(true).animate({
                top: '0',
            }, 250);
            $('.book-item-tool').stop(true).animate({
                bottom: 0,
            }, 250);
        }
    });

    $(window).scroll($.debounce(30, function () {
        let body = $('body');
        if (!body.hasClass('dark')) {
            return;
        }
        let st = $(window).scrollTop();
        if (st > 100) {
            $('.header').stop(true).animate({
                top: '-50px',
            }, 250);
            $('.book-item-tool').stop(true).animate({
                bottom: '-50px',
            }, 250);
        } else {
            $('.header').stop(true).animate({
                top: '0',
            }, 250);
            $('.book-item-tool').stop(true).animate({
                bottom: 0,
            }, 250);
        }
    }));

    $('.carousel-body a').hover(function () {
        let src = $(this).find('img').attr('src');
        $('.carousel-bg').attr('style', "background-image: url('" + src + "')")
    })
});